//
//  DOPDropDownMenu.m
//  DOPDropDownMenuDemo
//
//  Created by weizhou on 9/26/14.
//  Copyright (c) 2014 fengweizhou. All rights reserved.
//

#import "DOPDropDownMenu.h"
#import "NSDate+EUHelper.h"

@implementation DOPIndexPath
- (instancetype)initWithColumn:(NSInteger)column row:(NSInteger)row {
    self = [super init];
    if (self) {
        _column = column;
        _row = row;
    }

    return self;
}

+ (instancetype)indexPathWithCol:(NSInteger)col row:(NSInteger)row {
    DOPIndexPath *indexPath = [[self alloc] initWithColumn:col row:row];
    return indexPath;
}
@end

#pragma mark - menu implementation

@interface DOPDropDownMenu ()
@property(nonatomic, assign) NSInteger currentSelectedMenudIndex;
@property(nonatomic, assign) BOOL show;
@property(nonatomic, assign) NSInteger numOfMenu;
@property(nonatomic, assign) CGPoint origin;
@property(nonatomic, strong) UIView *backGroundView;
@property(nonatomic, strong) UITableView *tableView;
// data source
@property(nonatomic, copy) NSArray *array;
// layers array
@property(nonatomic, strong) NSMutableArray *titles;
@property(nonatomic, copy) NSArray *indicators;
@property(nonatomic, copy) NSArray *bgLayers;

@property(nonatomic, strong) UIView *otherBackView;
//@property(nonatomic, strong) TZDatePickerView *datePicker; // 日期选择器
@end

@implementation DOPDropDownMenu

#pragma mark - getter
- (UIColor *)indicatorColor {
    if (!_indicatorColor) {
        _indicatorColor = [UIColor blackColor];
    }
    return _indicatorColor;
}

- (UIColor *)textColor {
    if (!_textColor) {
        _textColor = [UIColor blackColor];
    }
    return _textColor;
}

- (UIColor *)separatorColor {
    if (!_separatorColor) {
        _separatorColor = [UIColor blackColor];
    }
    return _separatorColor;
}

- (NSString *)titleForRowAtIndexPath:(DOPIndexPath *)indexPath {
    return [self.dataSource menu:self titleForRowAtIndexPath:indexPath];
}

#pragma mark - setter
float dateWight=13*9.0+16;
- (void)setDataSource:(id<DOPDropDownMenuDataSource>)dataSource {
    _dataSource = dataSource;
    _titles = [NSMutableArray arrayWithCapacity:0];
    // configure view
    if ([_dataSource respondsToSelector:@selector(numberOfColumnsInMenu:)]) {
        _numOfMenu = [_dataSource numberOfColumnsInMenu:self];
    } else {
        _numOfMenu = 1;
    }

    
    CGFloat textLayerInterval=0.0;
    CGFloat bgLayerInterval = 0.0 ;
    
    
    CGFloat firstUnAveTextLayerInterval=0.0;
    CGFloat firstUnAveBgLayerInterval = 0.0 ;

    if (self.isUnAverageWight) {
        NSString *titleString = [_dataSource menu:self titleForRowAtIndexPath:[DOPIndexPath indexPathWithCol:self.isUnAverageNum row:0]];
        titleString=[titleString substringToIndex:13];
        firstUnAveTextLayerInterval=dateWight/2;
        firstUnAveBgLayerInterval=dateWight;
        if(self.frame.size.width / (_numOfMenu * 2)>firstUnAveTextLayerInterval){
            firstUnAveTextLayerInterval=self.frame.size.width / (_numOfMenu * 2);
            firstUnAveBgLayerInterval=self.frame.size.width / _numOfMenu;
            textLayerInterval= self.frame.size.width / (_numOfMenu * 2);
            bgLayerInterval=self.frame.size.width / _numOfMenu;
        }else{
            float otherWight=self.frame.size.width-dateWight;
            textLayerInterval= otherWight / ((_numOfMenu-1) * 2);
            bgLayerInterval=otherWight / (_numOfMenu-1);
        }
        
    }else{
        textLayerInterval= self.frame.size.width / (_numOfMenu * 2);
        bgLayerInterval=self.frame.size.width / _numOfMenu;
    }
    
    NSMutableArray *tempTitles = [[NSMutableArray alloc] initWithCapacity:_numOfMenu];
    NSMutableArray *tempIndicators = [[NSMutableArray alloc] initWithCapacity:_numOfMenu];
    NSMutableArray *tempBgLayers = [[NSMutableArray alloc] initWithCapacity:_numOfMenu];

    for (int i = 0; i < _numOfMenu; i++) {
        // bgLayer
        CGPoint bgLayerPosition;
        if (self.isUnAverageWight ) {
            if (i==0) {
                bgLayerPosition= CGPointMake((i + 0.5) * firstUnAveBgLayerInterval, self.frame.size.height / 2);
            }else{
                bgLayerPosition= CGPointMake((i-1 + 0.5) *bgLayerInterval + firstUnAveBgLayerInterval, self.frame.size.height / 2);
            }
            
        }else{
            bgLayerPosition= CGPointMake((i + 0.5) * bgLayerInterval, self.frame.size.height / 2);
        }
        CALayer *bgLayer = [self createBgLayerWithColor:[UIColor whiteColor] andPosition:bgLayerPosition];
        [self.layer addSublayer:bgLayer];
        [tempBgLayers addObject:bgLayer];
        // title
        CGPoint titlePosition;
        if (self.isUnAverageWight) {
            if (i==0) {
                titlePosition= CGPointMake(firstUnAveTextLayerInterval, self.frame.size.height / 2);
            }else{
                titlePosition= CGPointMake(((i-1) * 2 + 1) * textLayerInterval + 2*firstUnAveTextLayerInterval, self.frame.size.height / 2);
            }
            
        }else{
            titlePosition= CGPointMake((i * 2 + 1) * textLayerInterval, self.frame.size.height / 2);
        }
        NSString *titleString = [_dataSource menu:self titleForRowAtIndexPath:[DOPIndexPath indexPathWithCol:i row:0]];
        CATextLayer *title = [self createTextLayerWithNSString:titleString withColor:self.textColor andPosition:titlePosition];
        
        [self.layer addSublayer:title];
        [tempTitles addObject:title];
        // indicator
        CAShapeLayer *indicator ;
        if (self.isUnAverageWight&&i==0) {
            indicator=[self createIndicatorWithColor:self.indicatorColor
                                             andPosition:CGPointMake(titlePosition.x + (dateWight-16)/2, self.frame.size.height / 2)];
            indicator.zPosition=10;
        }else{
            indicator=[self createIndicatorWithColor:self.indicatorColor
                                         andPosition:CGPointMake(titlePosition.x + title.bounds.size.width / 2 + 8, self.frame.size.height / 2)];
        }
        [self.layer addSublayer:indicator];
        [tempIndicators addObject:indicator];
        
        
        
        
        if (self.isCutOffLine) {
            CAShapeLayer *cutOffLine;
            CGPoint lineLayerPosition;
            if (self.isUnAverageWight) {
                if (i==0) {
                    lineLayerPosition= CGPointMake(firstUnAveBgLayerInterval, self.frame.size.height / 2);
                }else{
                    lineLayerPosition= CGPointMake(firstUnAveBgLayerInterval+i*bgLayerInterval, self.frame.size.height / 2);
                }
            }else{
                lineLayerPosition= CGPointMake(bgLayerInterval, self.frame.size.height / 2);
            }

            cutOffLine=[self createCutOffLineWithColor:[UIColor lightGrayColor] andPosition:lineLayerPosition];
            [self.layer addSublayer:cutOffLine];
            [tempIndicators addObject:cutOffLine];
        }
    }
    _titles = [NSMutableArray arrayWithArray:tempTitles];
    _indicators = [tempIndicators copy];
    _bgLayers = [tempBgLayers copy];
}

#pragma mark - init method
- (instancetype)initWithOrigin:(CGPoint)origin andHeight:(CGFloat)height {
    CGSize screenSize = [UIScreen mainScreen].bounds.size;
    self = [self initWithFrame:CGRectMake(origin.x, origin.y, screenSize.width, height)];
    if (self) {
        _origin = origin;
        _currentSelectedMenudIndex = -1;
        _show = NO;

        // tableView init
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(origin.x, self.frame.origin.y + self.frame.size.height, self.frame.size.width, 0)
                                                  style:UITableViewStylePlain];
        _tableView.rowHeight = 38;
        _tableView.dataSource = self;
        _tableView.delegate = self;
//        _tableView.scrollEnabled = NO;
        _otherBackView = [[UIView alloc]init];
        _otherBackView.layer.masksToBounds = YES;
        _otherBackView.backgroundColor = [UIColor whiteColor];
        // self tapped
        self.backgroundColor = [UIColor whiteColor];
        UIGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(menuTapped:)];
        [self addGestureRecognizer:tapGesture];

        // background init and tapped
        _backGroundView = [[UIView alloc] initWithFrame:CGRectMake(origin.x, origin.y, screenSize.width, screenSize.height)];
        _backGroundView.backgroundColor = [UIColor colorWithWhite:0.0 alpha:0.0];
        _backGroundView.opaque = NO;
        UIGestureRecognizer *gesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(backgroundTapped:)];
        [_backGroundView addGestureRecognizer:gesture];

        // add bottom shadow
        UIView *bottomShadow = [[UIView alloc] initWithFrame:CGRectMake(0, self.frame.size.height - 0.5, screenSize.width, 0.5)];
        bottomShadow.backgroundColor = [UIColor lightGrayColor];
        [self addSubview:bottomShadow];
    }

    return self;
}

#pragma mark - init support
- (CALayer *)createBgLayerWithColor:(UIColor *)color andPosition:(CGPoint)position {
    CALayer *layer = [CALayer layer];
    layer.position = position;
    
    if (self.isUnAverageWight ) {
        if ( position.x<=(dateWight/2)) {
            
            layer.bounds = CGRectMake(0, 0, dateWight, self.frame.size.height - 1);
        }else{
            
            layer.bounds = CGRectMake(0, 0, (self.frame.size.width-dateWight) / (self.numOfMenu-1), self.frame.size.height - 1);
        }
    }else{
        layer.bounds = CGRectMake(0, 0, self.frame.size.width / self.numOfMenu, self.frame.size.height - 1);
    }
       layer.backgroundColor =color.CGColor;
        NSLog(@"bglayer bounds:%@",NSStringFromCGRect(layer.bounds));
        NSLog(@"bglayer position:%@", NSStringFromCGPoint(position));

    return layer;
}

-(CAShapeLayer *)createCutOffLineWithColor:(UIColor *)color andPosition:(CGPoint)point{
    CAShapeLayer *layer=[CAShapeLayer new];
    
    UIBezierPath * path=[UIBezierPath new];
    [path moveToPoint:CGPointMake(0, 0)];
    [path addLineToPoint:CGPointMake(0.5, 0)];
    [path addLineToPoint:CGPointMake(0.5, 30)];
    [path addLineToPoint:CGPointMake(0, 30)];
    [path closePath];
    
    
    layer.path = path.CGPath;
    layer.lineWidth = 0.5;
    layer.fillColor =color.CGColor;
    
    
    CGPathRef bound = CGPathCreateCopyByStrokingPath(layer.path, nil, layer.lineWidth, kCGLineCapButt, kCGLineJoinMiter, layer.miterLimit);
    layer.bounds = CGPathGetBoundingBox(bound);
    CGPathRelease(bound);
    
    layer.position = point;
    
    return layer;
}

- (CAShapeLayer *)createIndicatorWithColor:(UIColor *)color andPosition:(CGPoint)point {
    CAShapeLayer *layer = [CAShapeLayer new];
    UIBezierPath *path = [UIBezierPath new];
    [path moveToPoint:CGPointMake(0, 0)];
    [path addLineToPoint:CGPointMake(8, 0)];
    [path addLineToPoint:CGPointMake(4, 5)];
    [path closePath];

    layer.path = path.CGPath;
    layer.lineWidth = 1.0;
    layer.fillColor =color.CGColor;

    CGPathRef bound = CGPathCreateCopyByStrokingPath(layer.path, nil, layer.lineWidth, kCGLineCapButt, kCGLineJoinMiter, layer.miterLimit);
    layer.bounds = CGPathGetBoundingBox(bound);
    CGPathRelease(bound);

    layer.position = point;

    return layer;
}

- (CATextLayer *)createTextLayerWithNSString:(NSString *)string withColor:(UIColor *)color andPosition:(CGPoint)point {

    CGSize size = [self calculateTitleSizeWithString:string];

    CATextLayer *layer = [CATextLayer new];
    CGFloat sizeWidth =0.0;
    if (self.isUnAverageWight ) {
        if ( point.x<=dateWight) {
            sizeWidth=size.width<dateWight?size.width:dateWight;
        }else{
            float otherWight=self.frame.size.width-dateWight;
            sizeWidth= (size.width < (otherWight / (_numOfMenu-1)) - 25) ? size.width : otherWight / (_numOfMenu-1) - 25;
        }
    }else{
        sizeWidth= (size.width < (self.frame.size.width / _numOfMenu) - 25) ? size.width : self.frame.size.width / _numOfMenu - 25;
    }
    
    layer.bounds = CGRectMake(0, 0, sizeWidth, size.height);
    layer.string = string;
    layer.fontSize = 14.0;
    layer.alignmentMode = kCAAlignmentCenter;
    layer.foregroundColor = color.CGColor;

    layer.contentsScale = [[UIScreen mainScreen] scale];

    layer.position = point;

    return layer;
}

- (CGSize)calculateTitleSizeWithString:(NSString *)string {
    CGFloat fontSize = 14.0;
    NSDictionary *dic = @{NSFontAttributeName : [UIFont systemFontOfSize:fontSize]};
    CGSize size = [string boundingRectWithSize:CGSizeMake(280, 0)
                                       options:NSStringDrawingTruncatesLastVisibleLine | NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading
                                    attributes:dic
                                       context:nil]
                      .size;
    return size;
}

#pragma mark - gesture handle
//判断是否显示除下拉菜单意外的界面（由外部传入）
/*
 return NO-不需要，只展示下拉菜单即可
 return YES-需要展示外部传入界面
 */
-(BOOL)judgeIsShowOtherViewWithColumnNum:(NSInteger)columnNum{
    NSArray * allCoumns = self.otherView.allKeys;
    NSString * currentCoumn = [NSString stringWithFormat:@"columnNum%ld",(long)columnNum];
    if (self.isAddOtherView && [allCoumns containsObject:currentCoumn]) {
        return YES;
    }else{
        return NO;
    }
    
}

- (void)menuTapped:(UITapGestureRecognizer *)paramSender {
    CGPoint touchPoint = [paramSender locationInView:self];
    // calculate index
    NSInteger tapIndex = touchPoint.x / (self.frame.size.width / _numOfMenu);

    for (int i = 0; i < _numOfMenu; i++) {
        if (i != tapIndex) {
            [self animateIndicator:_indicators[i]
                           Forward:NO
                          complete:^{
                              [self animateTitle:_titles[i]
                                            show:NO
                                        complete:^{

                                        }];
                          }];
            [(CALayer *)self.bgLayers[i] setBackgroundColor:[UIColor whiteColor].CGColor];
        }
    }
    
//    if ([self judgeIsShowOtherViewWithColumnNum:tapIndex]) {
//        _currentSelectedMenudIndex = tapIndex;
//        [self animateIdicator:_indicators[_currentSelectedMenudIndex]
//                   background:_backGroundView
//                    tableView:_tableView
//                        title:_titles[_currentSelectedMenudIndex]
//                      forward:NO
//                    complecte:^{
//                        if ([self.delegate respondsToSelector:@selector(menu:numberOfSectionAtIndexPath:)]) {
//                            [self.delegate menu:self numberOfSectionAtIndexPath:tapIndex];
//                        }
//                        _show = NO;
//                    }];
//        [(CALayer *)self.bgLayers[tapIndex] setBackgroundColor:[UIColor whiteColor].CGColor];
//        return;
//    }

    if (tapIndex == _currentSelectedMenudIndex && _show) {
//        if ([self judgeIsShowOtherViewWithColumnNum:tapIndex]) {
//            [self animateIdicator:_indicators[_currentSelectedMenudIndex]
//                       background:_backGroundView
//                             View:nil
//                            title:_titles[_currentSelectedMenudIndex]
//                          forward:NO
//                        complecte:^{
//                            _currentSelectedMenudIndex = tapIndex;
//                            // if (_datePicker) [self.datePicker removeFromSuperview];
//                            _show = NO;
//                        }];
//        } else {
            _tableView.hidden = NO;
            [self animateIdicator:_indicators[_currentSelectedMenudIndex]
                       background:_backGroundView
                        tableView:_tableView
                            title:_titles[_currentSelectedMenudIndex]
                          forward:NO
                        complecte:^{
                            _currentSelectedMenudIndex = tapIndex;
                            _show = NO;
                        }];
//        }
        [(CALayer *)self.bgLayers[tapIndex] setBackgroundColor:[UIColor whiteColor].CGColor];
    } else {
        _currentSelectedMenudIndex = tapIndex;
//        if ([self judgeIsShowOtherViewWithColumnNum:tapIndex]) {
//            [_tableView reloadData];
//            _tableView.hidden = YES;
//            [self animateIdicator:_indicators[tapIndex]
//                       background:_backGroundView
//                             View:nil
//                            title:_titles[tapIndex]
//                          forward:YES
//                        complecte:^{
//
//                            _show = YES;
//                        }];
//        } else {
            _tableView.hidden = NO;
            [_tableView reloadData];
            [self animateIdicator:_indicators[tapIndex]
                       background:_backGroundView
                        tableView:_tableView
                            title:_titles[tapIndex]
                          forward:YES
                        complecte:^{
                            _show = YES;
                        }];
//        }
        [(CALayer *)self.bgLayers[tapIndex] setBackgroundColor:[UIColor colorWithWhite:0.9 alpha:1.0].CGColor];
    }
}

- (void)backgroundTapped:(UITapGestureRecognizer *)paramSender {
    [self animateIdicator:_indicators[_currentSelectedMenudIndex]
               background:_backGroundView
                tableView:_tableView
                    title:_titles[_currentSelectedMenudIndex]
                  forward:NO
                complecte:^{
                    _show = NO;
                }];
    [(CALayer *)self.bgLayers[_currentSelectedMenudIndex] setBackgroundColor:[UIColor whiteColor].CGColor];

    [self animateIdicator:_indicators[_currentSelectedMenudIndex]
               background:_backGroundView
                     View:nil
                    title:_titles[_currentSelectedMenudIndex]
                  forward:NO
                complecte:^{
                    _currentSelectedMenudIndex = 2;
                    // if (_datePicker) [self.datePicker removeFromSuperview];
                    _show = NO;
                }];
}

#pragma mark - animation method
//旋转3角形
- (void)animateIndicator:(CAShapeLayer *)indicator Forward:(BOOL)forward complete:(void (^)(void))complete {
    [CATransaction begin];
    [CATransaction setAnimationDuration:0.25];
    [CATransaction setAnimationTimingFunction:[CAMediaTimingFunction functionWithControlPoints:0.4:0.0:0.2:1.0]];

    CAKeyframeAnimation *anim = [CAKeyframeAnimation animationWithKeyPath:@"transform.rotation"];
    anim.values = forward ? @[ @0, @(M_PI) ] : @[ @(M_PI), @0 ];

    if (!anim.removedOnCompletion) {
        [indicator addAnimation:anim forKey:anim.keyPath];
    } else {
        [indicator addAnimation:anim forKey:anim.keyPath];
        [indicator setValue:anim.values.lastObject forKeyPath:anim.keyPath];
    }

    [CATransaction commit];

    complete();
}

- (void)animateBackGroundView:(UIView *)view show:(BOOL)show complete:(void (^)(void))complete {
    if (show) {
        [self.superview addSubview:view];
        [view.superview addSubview:self];

        [UIView animateWithDuration:0.2
                         animations:^{
                             view.backgroundColor = [UIColor colorWithWhite:0.0 alpha:0.3];
                         }];
    } else {
        [UIView animateWithDuration:0.2
            animations:^{
                view.backgroundColor = [UIColor colorWithWhite:0.0 alpha:0.0];
            }
            completion:^(BOOL finished) {
                [view removeFromSuperview];
            }];
    }
    complete();
}

- (void)animateTableView:(UITableView *)tableView show:(BOOL)show complete:(void (^)(void))complete {
    
    if ([self judgeIsShowOtherViewWithColumnNum:_currentSelectedMenudIndex]) {
        NSString * currentCoumn = [NSString stringWithFormat:@"columnNum%ld",_currentSelectedMenudIndex];
        UIView * view = _otherView[currentCoumn];
        float viewHeight = CGRectGetHeight(view.frame);
        
        view.frame =  CGRectMake(0, -viewHeight, self.frame.size.width, viewHeight);
        self.otherBackView.frame = CGRectMake(self.origin.x, self.frame.origin.y + self.frame.size.height, self.frame.size.width, 0);
        if (show) {
            [self.otherBackView removeAllSubviews];
            [self.otherBackView addSubview:view];
            [self.superview addSubview:self.otherBackView];
            [UIView animateWithDuration:0.2
                          animations:^{
                              self.otherBackView.frame = CGRectMake(self.origin.x, self.frame.origin.y + self.frame.size.height, self.frame.size.width, viewHeight);

                              view.frame =  CGRectMake(0, 0, self.frame.size.width, viewHeight);
                          }];
        }else{
            [UIView animateWithDuration:0.1
                          animations:^{
                              self.otherBackView.frame = CGRectMake(self.origin.x, self.frame.origin.y + self.frame.size.height, self.frame.size.width, 0);
                              view.frame =  CGRectMake(0, -viewHeight, self.frame.size.width, viewHeight);
                          }
                          completion:^(BOOL finished) {
                              [view removeFromSuperview];
                          }];
        }
        show = NO;
    }else{
        [self.otherBackView removeAllSubviews];
        [UIView animateWithDuration:0.1
                         animations:^{
                             self.otherBackView.frame = CGRectMake(self.origin.x, self.frame.origin.y + self.frame.size.height, self.frame.size.width, 0);
                         }completion:^(BOOL finished) {
                             [self.otherBackView removeFromSuperview];
                         }];
    }
    
    
    if (show) {
        tableView.frame = CGRectMake(self.origin.x, self.frame.origin.y + self.frame.size.height, self.frame.size.width, 0);
        [self.superview addSubview:tableView];
        CGFloat tableViewHeight;
        if (!self.mostRowNum) {
            tableViewHeight = ([tableView numberOfRowsInSection:0] * tableView.rowHeight);
        }else{
            self.mostRowNum = 5;
            tableViewHeight = ([tableView numberOfRowsInSection:0] > self.mostRowNum) ? (self.mostRowNum * tableView.rowHeight) : ([tableView numberOfRowsInSection:0] * tableView.rowHeight);
        }

        [UIView animateWithDuration:0.2
                         animations:^{
                             _tableView.frame = CGRectMake(self.origin.x, self.frame.origin.y + self.frame.size.height, self.frame.size.width, tableViewHeight);
                         }];
    } else {
        [UIView animateWithDuration:0.2
            animations:^{
                _tableView.frame = CGRectMake(self.origin.x, self.frame.origin.y + self.frame.size.height, self.frame.size.width, 0);
            }
            completion:^(BOOL finished) {
                [tableView removeFromSuperview];
            }];
    }
    complete();
}

- (void)animateTitle:(CATextLayer *)title show:(BOOL)show complete:(void (^)(void))complete {
    
    CGSize size = [self calculateTitleSizeWithString:title.string];
    CGFloat sizeWidth =0.0;
    if (self.isUnAverageWight ) {
        CATextLayer * firText=_titles.firstObject;
        if ([firText.string isEqualToString:title.string]) {
            sizeWidth=size.width<dateWight?size.width:dateWight;
        }else{
            float otherWight=self.frame.size.width-dateWight;
            sizeWidth= (size.width < (otherWight / (_numOfMenu-1)) - 25) ? size.width : otherWight / (_numOfMenu-1) - 25;
        }
    }
    if (!sizeWidth) {
        sizeWidth = (size.width < (self.frame.size.width / _numOfMenu) - 25) ? size.width : self.frame.size.width / _numOfMenu - 25;
    }
    title.bounds = CGRectMake(0, 0, sizeWidth, size.height);
    complete();
}

- (void)animateIdicator:(CAShapeLayer *)indicator
             background:(UIView *)background
              tableView:(UITableView *)tableView
                  title:(CATextLayer *)title
                forward:(BOOL)forward
              complecte:(void (^)(void))complete {

    [self animateIndicator:indicator
                   Forward:forward
                  complete:^{
                      [self animateTitle:title
                                    show:forward
                                complete:^{
                                    [self animateBackGroundView:background
                                                           show:forward
                                                       complete:^{
                                                           [self animateTableView:tableView
                                                                             show:forward
                                                                         complete:^{

                                                                         }];
                                                       }];
                                }];
                  }];

    complete();
}

- (void)animateIdicator:(CAShapeLayer *)indicator
             background:(UIView *)background
                   View:(UIView *)View
                  title:(CATextLayer *)title
                forward:(BOOL)forward
              complecte:(void (^)(void))complete {
    //  CATextLayer * title2 = (CATextLayer *)_titles[2];
    //  NSLog(@"%@",title2.string);
    [self animateIndicator:indicator
                   Forward:forward
                  complete:^{
                      [self animateTitle:title
                                    show:forward
                                complete:^{
                                    [self animateBackGroundView:background
                                                           show:forward
                                                       complete:^{
                                                          
                                                       }];
                                }];
                  }];

    complete();
}

#pragma mark - table datasource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    NSAssert(self.dataSource != nil, @"menu's dataSource shouldn't be nil");
    if ([self.dataSource respondsToSelector:@selector(menu:numberOfRowsInColumn:)]) {
        return [self.dataSource menu:self numberOfRowsInColumn:self.currentSelectedMenudIndex];
    } else {
        NSAssert(0 == 1, @"required method of dataSource protocol should be implemented");
        return 0;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *identifier = @"DropDownMenuCell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
    }
    NSAssert(self.dataSource != nil, @"menu's datasource shouldn't be nil");
    if ([self.dataSource respondsToSelector:@selector(menu:titleForRowAtIndexPath:)]) {
        cell.textLabel.text =
            [self.dataSource menu:self titleForRowAtIndexPath:[DOPIndexPath indexPathWithCol:self.currentSelectedMenudIndex row:indexPath.row]];
    } else {
        NSAssert(0 == 1, @"dataSource method needs to be implemented");
    }
    cell.backgroundColor = [UIColor whiteColor];
    cell.textLabel.font = [UIFont systemFontOfSize:14.0];
    cell.separatorInset = UIEdgeInsetsZero;

    if ([cell.textLabel.text isEqualToString:[(CATextLayer *)[_titles objectAtIndex:_currentSelectedMenudIndex] string]]) {
        cell.backgroundColor = [UIColor colorWithWhite:0.9 alpha:1.0];
    }

    return cell;
}

#pragma mark - tableview delegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [self confiMenuWithSelectRow:indexPath.row];
    if (self.delegate || [self.delegate respondsToSelector:@selector(menu:didSelectRowAtIndexPath:)]) {
        [self.delegate menu:self didSelectRowAtIndexPath:[DOPIndexPath indexPathWithCol:self.currentSelectedMenudIndex row:indexPath.row]];
    }
}

- (void)confiMenuWithSelectRow:(NSInteger)row {
    CATextLayer *title = (CATextLayer *)_titles[_currentSelectedMenudIndex];
    title.string = [self.dataSource menu:self titleForRowAtIndexPath:[DOPIndexPath indexPathWithCol:self.currentSelectedMenudIndex row:row]];

    [self animateIdicator:_indicators[_currentSelectedMenudIndex]
               background:_backGroundView
                tableView:_tableView
                    title:_titles[_currentSelectedMenudIndex]
                  forward:NO
                complecte:^{
                    _show = NO;
                }];
    [(CALayer *)self.bgLayers[_currentSelectedMenudIndex] setBackgroundColor:[UIColor whiteColor].CGColor];

    CAShapeLayer *indicator = (CAShapeLayer *)_indicators[_currentSelectedMenudIndex];
    indicator.position = CGPointMake(title.position.x + title.frame.size.width / 2 + 8, indicator.position.y);
}

- (void)dismiss {
    [self backgroundTapped:nil];
}

///返回当前视图的控制器 UIViewController * presentCtr= [self getCurrentRootViewController];
- (UIViewController *)getCurrentRootViewController {
    UIViewController *result;
    UIWindow *topWindow = [[UIApplication sharedApplication] keyWindow];
    if (topWindow.windowLevel != UIWindowLevelNormal) {
        NSArray *windows = [[UIApplication sharedApplication] windows];
        for (topWindow in windows) {
            if (topWindow.windowLevel == UIWindowLevelNormal)
                break;
        }
    }
    UIView *rootView = [[topWindow subviews] objectAtIndex:0];
    id nextResponder = [rootView nextResponder];
    if ([nextResponder isKindOfClass:[UIViewController class]])
        result = nextResponder;
    else if ([topWindow respondsToSelector:@selector(rootViewController)] && topWindow.rootViewController != nil)
        result = topWindow.rootViewController;
    else
        NSAssert(NO, @"ShareKit: Could not find a root view controller.  You can assign one manually by calling [[SHK currentHelper] "
                     @"setRootViewController:YOURROOTVIEWCONTROLLER].");
    return result;
}
//
//- (void)loadCalender {
//    _calendarView = [[UIView alloc] initWithFrame:CGRectMake(CGRectGetWidth(self.frame) * 0.1, 104, CGRectGetWidth(self.frame) * 0.8, 250)];
//    _calendarView.backgroundColor = [UIColor whiteColor];
//    _calendarView.layer.cornerRadius = 5;
//    _calendarView.layer.masksToBounds = YES;
//
//    // CGFloat height = [[UIDevice currentDevice].model hasPrefix:@"iPad"] ? 450 : 300;
//    FSCalendar *calendar = [[FSCalendar alloc] initWithFrame:CGRectMake(0, 0, CGRectGetWidth(self.frame) * 0.8, 200)];
//    // UIViewController *presentCtr = [self getCurrentRootViewController];
//
//    calendar.dataSource = self;
//    calendar.delegate = self;
//    //    calendar.delegate = presentCtr;
//    calendar.appearance.caseOptions = FSCalendarCaseOptionsHeaderUsesUpperCase; //| FSCalendarCaseOptionsWeekdayUsesUpperCase;
//    calendar.backgroundColor = [UIColor whiteColor];
//    calendar.identifier = NSCalendarIdentifierGregorian;
//
//    self.btnAllDates = [UIButton buttonWithType:UIButtonTypeCustom];
//    [self.btnAllDates setTitle:@"所有" forState:UIControlStateNormal];
//    self.btnAllDates.titleLabel.font = [UIFont systemFontOfSize:13];
//    self.btnAllDates.layer.borderColor = BARTITLECOLOR.CGColor;
//    self.btnAllDates.layer.borderWidth = 1;
//    self.btnAllDates.layer.cornerRadius = 5;
//    self.btnAllDates.layer.masksToBounds = YES;
//    [self.btnAllDates setTitleColor:BARTITLECOLOR forState:UIControlStateNormal];
//    [self.btnAllDates addTarget:self action:@selector(actionAlldates) forControlEvents:UIControlEventTouchUpInside];
//    self.calendar = calendar;
//
//    [self.calendarView addSubview:self.calendar];
//    [self.calendarView addSubview:self.btnAllDates];
//
//    [self.btnAllDates mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.centerX.equalTo(self.calendarView.mas_centerX);
//        make.bottom.equalTo(self.calendarView.mas_bottom).with.offset(-10);
//        make.width.mas_equalTo(80);
//        make.height.mas_equalTo(30);
//    }];
//}
//
//- (void)calendar:(FSCalendar *)calendar didSelectDate:(NSDate *)date {
//    // NSLog(@"%s %@", __FUNCTION__, [calendar stringFromDate:date format:@"yyyy-MM-dd HH:mm:ss"]);
//
//    NSDate *now = [NSDate date];
//    NSTimeInterval secondsInterval = [now timeIntervalSinceDate:date];
//    // NSLog(@"secondsInterval=  %lf",secondsInterval);
//    if (secondsInterval < 0) {
//        [self.delegate menu:self didSelectCalender:@"0"];
//        [self animateIdicator:_indicators[_numOfMenu-1]
//                   background:_backGroundView
//                         View:nil
//                        title:_titles[_numOfMenu-1]
//                      forward:NO
//                    complecte:^{
//                        // _currentSelectedMenudIndex = 1;
//                        // if (_datePicker) [self.datePicker removeFromSuperview];
//                        _show = NO;
//                    }];
//
//        return;
//    }
//
//    NSString *timer = [date stringWithFormat:@"MM-dd"];
//    NSString *completeTime = [date stringWithFormat:@"yyyy-MM-dd"];
//
//    [self.delegate menu:self didSelectCalender:completeTime];
//    //
//    //    CGPoint titlePosition = CGPointMake(266.6, 20.0);
//    //    CATextLayer *title = [self createTextLayerWithNSString:timer withColor:self.textColor andPosition:titlePosition];
//    //    [_titles replaceObjectAtIndex:2 withObject:title];
//    CATextLayer *title = (CATextLayer *)_titles[_numOfMenu-1];
//    title.string = timer;
//
//    [self animateIdicator:_indicators[_numOfMenu-1]
//               background:_backGroundView
//                     View:nil
//                    title:_titles[_numOfMenu-1]
//                  forward:NO
//                complecte:^{
//                    // _currentSelectedMenudIndex = 1;
//                    // if (_datePicker) [self.datePicker removeFromSuperview];
//                    _show = NO;
//                }];
//
//    [(CALayer *)self.bgLayers[_numOfMenu-1] setBackgroundColor:[UIColor whiteColor].CGColor];
//
//    [self confiMenuWithCalenserDate:timer];
//}
//
//- (void)actionAlldates {
//
//    // CGPoint titlePosition = CGPointMake(266.6, 20.0);
//    //    CATextLayer *title = [self createTextLayerWithNSString:@"所有时间" withColor:self.textColor andPosition:titlePosition];
//    //    [_titles replaceObjectAtIndex:2 withObject:title];
//    CATextLayer *title = (CATextLayer *)_titles[_numOfMenu-1];
//    title.string = @"所有时间";
//    [self.delegate menu:self didSelectCalender:@"所有时间"];
//
//    [self animateIdicator:_indicators[_numOfMenu-1]
//               background:_backGroundView
//                     View:nil
//                    title:_titles[_numOfMenu-1]
//                  forward:NO
//                complecte:^{
//                    // _currentSelectedMenudIndex = 1;
//                    // if (_datePicker) [self.datePicker removeFromSuperview];
//                    _show = NO;
//                }];
//
//    [(CALayer *)self.bgLayers[_numOfMenu-1] setBackgroundColor:[UIColor whiteColor].CGColor];
//
//    [self confiMenuWithCalenserDate:@"所有时间"];
//}
//
-(void)changeTitleStr:(NSString *)showStr sention:(NSInteger)sention{
    CATextLayer *title = (CATextLayer *)_titles[sention];
    title.string = showStr;
    [(CALayer *)self.bgLayers[sention] setBackgroundColor:[UIColor whiteColor].CGColor];
    [self confiMenuWithCalenserDate:showStr];
}
//
- (void)confiMenuWithCalenserDate:(NSString *)calender {
    CATextLayer *title = (CATextLayer *)_titles[_numOfMenu-1];
    NSLog(@"%@", title.string);
    //    title.string = calender;
    //[self.dataSource menu:self titleForRowAtIndexPath:[DOPIndexPath indexPathWithCol:self.currentSelectedMenudIndex row:row]];
    // NSLog(@"%@",title.string);
    [self animateIdicator:_indicators[_currentSelectedMenudIndex]
               background:_backGroundView
                tableView:_tableView
                    title:title //_titles[_currentSelectedMenudIndex]
                  forward:NO
                complecte:^{
                    _show = NO;
                }];

    [(CALayer *)self.bgLayers[_numOfMenu-1] setBackgroundColor:[UIColor whiteColor].CGColor];

    CAShapeLayer *indicator = (CAShapeLayer *)_indicators[_numOfMenu-1];
    indicator.position = CGPointMake(title.position.x + title.frame.size.width / 2 + 8, indicator.position.y);
}

@end
